import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import '../style/Home.css';
import { yanz, deng } from '../utlis/https';

function Home() {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        captcha: '',
    });
    const [errors, setErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [captchaCode, setCaptchaCode] = useState(''); // 存储接口返回的验证码
    const [countdown, setCountdown] = useState(0); // 倒计时秒数
    const [showError, setShowError] = useState(false); // 控制错误消息的显示动画
    const [showSuccessAnimation, setShowSuccessAnimation] = useState(false); // 控制登录成功动画的显示
    const countdownTimerRef = useRef(null); // 倒计时计时器引用

    // 处理输入变化
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value,
        }));
        // 清除对应字段的错误
        if (errors[name]) {
            setErrors((prevErrors) => ({
                ...prevErrors,
                [name]: '',
            }));
        }
        // 清除公共错误
        if (errors.common) {
            setShowError(false);
            setTimeout(() => {
                setErrors((prevErrors) => ({
                    ...prevErrors,
                    common: '',
                }));
            }, 300);
        }
    };

    // 从接口获取验证码
    const fetchCaptcha = async () => {
        // 如果正在倒计时，则不允许再次获取
        if (countdown > 0) return;

        try {
            const res = await yanz();
            if (res && res.msg) {
                setCaptchaCode(res.msg); // 存储验证码
                // 开始60秒倒计时
                setCountdown(60);
            } else {
                console.error('获取验证码失败: 响应数据格式错误');
                setErrors({ captcha: '获取验证码失败，请重试' });
            }
        } catch (err) {
            console.error('获取验证码失败:', err);
            setErrors({ captcha: '网络错误，请稍后重试' });
        }
    };

    // 处理倒计时
    useEffect(() => {
        if (countdown > 0) {
            countdownTimerRef.current = setInterval(() => {
                setCountdown((prevCount) => {
                    if (prevCount <= 1) {
                        clearInterval(countdownTimerRef.current);
                        return 0;
                    }
                    return prevCount - 1;
                });
            }, 1000);
        } else if (countdownTimerRef.current) {
            clearInterval(countdownTimerRef.current);
        }

        // 组件卸载时清除计时器
        return () => {
            if (countdownTimerRef.current) {
                clearInterval(countdownTimerRef.current);
            }
        };
    }, [countdown]);

    // 验证表单
    const validateForm = () => {
        const newErrors = {};

        if (!formData.username.trim()) {
            newErrors.username = '请输入用户名';
        }

        if (!formData.password) {
            newErrors.password = '请输入密码';
        } else if (formData.password.length < 6) {
            newErrors.password = '密码长度不能少于6位';
        }

        if (!formData.captcha) {
            newErrors.captcha = '请输入验证码';
        } else if (!captchaCode) {
            newErrors.captcha = '请先获取验证码';
        } else if (formData.captcha !== captchaCode) {
            newErrors.captcha = '验证码不正确';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // 处理表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (validateForm()) {
            setIsSubmitting(true);

            try {
                const loginParams = {
                    name: formData.username,
                    pwd: formData.password,
                    vercode: formData.captcha,
                };

                const res = await deng(loginParams);

                // 打印服务器返回的完整响应，便于调试
                console.log('服务器返回:', res)
                sessionStorage.setItem('userid', res.data[0].id);
                // 根据接口返回的状态码处理
                if (res.code === 0) {
                    // 登录成功，显示成功动画
                    setShowSuccessAnimation(true);

                    // 保存token等信息
                    // 延迟导航，让用户看到成功动画
                    setTimeout(() => {
                        navigate('/pgs');
                    }, 1500);
                } else {
                    // 登录失败，优化错误信息提示逻辑
                    const newErrors = {};

                    // 检查是否是验证码错误（优先级最高）
                    if (res.msg && (res.msg.includes('验证码') || res.msg.includes('vercode') || res.msg.includes('Vercode'))) {
                        newErrors.captcha = '验证码错误';
                        // 验证码错误时刷新验证码，但不重置倒计时
                        if (countdown <= 0) {
                            fetchCaptcha();
                        }
                    }
                    // 检查是否是用户名或密码错误
                    else if (res.msg && (res.msg.includes('用户名') || res.msg.includes('密码') ||
                        res.msg.includes('name') || res.msg.includes('pwd') || res.msg.includes('账号'))) {
                        newErrors.common = '用户名或密码错误';
                        setShowError(true);
                    }
                    // 优化：如果服务器返回了错误但没有明确指出类型，我们直接设置为用户名或密码错误
                    else {
                        // 优先判断是否是验证码格式问题
                        if (!formData.captcha || formData.captcha !== captchaCode) {
                            newErrors.captcha = '验证码错误';
                            if (countdown <= 0) {
                                fetchCaptcha();
                            }
                        } else {
                            // 其他情况默认显示用户名或密码错误，而不是模糊的"登录失败"
                            newErrors.common = '用户名或密码错误';
                            setShowError(true);
                        }
                    }

                    setErrors(newErrors);
                }
            } catch (err) {
                console.error('登录请求失败:', err);
                setErrors({ common: '网络错误，请稍后重试' });
                setShowError(true);
            } finally {
                setIsSubmitting(false);
            }
        }
    };

    return (
        <div className="login-container">
            <div className="login-box animate__fadeIn">
                <h2 className="login-title">欢迎登录</h2>
                <form onSubmit={handleSubmit} className="login-form">
                    {errors.common && (
                        <div className={`common-error-message ${showError ? 'animate__fadeIn' : ''}`}>
                            {errors.common}
                        </div>
                    )}

                    <div className="form-group">
                        <label htmlFor="username">用户名</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            value={formData.username}
                            onChange={handleChange}
                            placeholder="请输入用户名"
                            className={errors.username ? 'error' : ''}
                            autoComplete="username"
                        />
                        {errors.username && <span className="error-message">{errors.username}</span>}
                    </div>

                    <div className="form-group">
                        <label htmlFor="password">密码</label>
                        <input
                            type="password"
                            id="password"
                            name="password"
                            value={formData.password}
                            onChange={handleChange}
                            placeholder="请输入密码"
                            className={errors.password ? 'error' : ''}
                            autoComplete="current-password"
                        />
                        {errors.password && <span className="error-message">{errors.password}</span>}
                    </div>

                    <div className="form-group">
                        <label htmlFor="captcha">验证码</label>
                        <div className="captcha-container">
                            <input
                                type="text"
                                id="captcha"
                                name="captcha"
                                value={formData.captcha}
                                onChange={handleChange}
                                placeholder="请输入验证码"
                                className={errors.captcha ? 'error' : ''}
                                autoComplete="one-time-code"
                            />
                            <button
                                type="button"
                                className="captcha-button"
                                onClick={fetchCaptcha}
                                disabled={countdown > 0}
                                title={countdown > 0 ? `请等待${countdown}秒后重试` : '获取验证码'}
                            >
                                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                            </button>
                        </div>
                        {errors.captcha && <span className="error-message">{errors.captcha}</span>}
                        {/* 验证码显示区域 */}
                        {captchaCode && (
                            <div className="captcha-display animate__fadeIn">
                                <span className="captcha-code">{captchaCode}</span>
                            </div>
                        )}
                    </div>

                    <button
                        type="submit"
                        className={`login-button ${isSubmitting ? 'loading' : ''}`}
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? (
                            <>
                                <span className="loading-spinner"></span>
                                <span>登录中...</span>
                            </>
                        ) : '登录'}
                    </button>
                </form>
                <p className='Home_q1 hover-effect' onClick={() => navigate('/about')}>没有账号? 立即注册</p>
            </div>

            {/* 登录成功动画 */}
            {showSuccessAnimation && (
                <div className="success-animation-overlay">
                    <div className="success-animation">
                        <div className="success-checkmark">
                            <svg viewBox="0 0 52 52">
                                <path className="success-checkmark-circle" d="M50.4 14.8c-1.6-1.2-3.6-1.8-5.6-1.8s-4 .6-5.6 1.8L26 25.7 12.8 14.8C11.2 13.6 9.2 13 7.2 13S3.6 13.6 2 14.8l-1.2 1c-.8.7-1.2 1.6-1.2 2.6 0 2 .8 3.8 2.4 5.2l18 16c1.6 1.4 3.6 2.2 5.6 2.2s4-.8 5.6-2.2l18-16c1.6-1.4 2.4-3.2 2.4-5.2 0-1-.4-1.9-1.2-2.6l-1.2-1z" />
                                <path className="success-checkmark-stem" d="M14 28l11 9 20-18" />
                                <path className="success-checkmark-kick" d="M35.5 19.2l-11 9-11-9" />
                            </svg>
                        </div>
                        <p className="success-message">登录成功！正在进入首页...</p>
                    </div>
                </div>
            )}
        </div>
    );
}

export default Home;